package de.preisrobot.business.parser;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import net.htmlparser.jericho.Element;
import net.htmlparser.jericho.Source;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.log4j.Logger;

import de.preisrobot.entity.ArtikelDetail;
import de.preisrobot.entity.ArtikelProperty;
import de.preisrobot.service.helper.HttpClientFactory;
import de.preisrobot.service.internal.PreisRobotParserException;

public abstract class AbstractArtikelDetailParser
{
   private static Logger logger = Logger.getLogger(AbstractArtikelDetailParser.class);

   public ArtikelDetail parse(String sourceUrlString) throws Exception
   {
      new ArrayList<ArtikelProperty>();

      if (sourceUrlString == null || sourceUrlString.length() == 0)
         throw new RuntimeException("Using default argument of \"" + sourceUrlString + '"');

      HttpClient client = HttpClientFactory.getHttpClient();
      GetMethod method = HttpClientFactory.createGETMethod(sourceUrlString);
      client.executeMethod(method);

      try
      {

         InputStream in = method.getResponseBodyAsStream();
         return parseStream( in);

      }
      catch (PreisRobotParserException e)
      {
         throw e;
      }
      catch (Exception e)
      {

         logger.error(e);

      }
      finally
      {

         method.releaseConnection();
      }
      return null;
   }

   protected abstract ArtikelDetail parseStream(InputStream in) throws IOException, PreisRobotParserException;

   protected abstract  Set<ArtikelProperty> parseArtikelEigenschaften(Element rootArtikelItem);

   protected abstract String parsePreis(Source source);
 

}
